//
//  PHInfoViewController.m
//  PhnixHome
//
//  Created by Levy Xu on 2017/12/29.
//  Copyright © 2017年 Levy Xu. All rights reserved.
//

#import "PHInfoViewController.h"
#import "KKDatePicker.h"
#import "CameraUtils.h"
#import "KKDialogTextViewController.h"
#import <RSKImageCropper/RSKImageCropper.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "PHPasswordViewController.h"

@interface PHInfoViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate, RSKImageCropViewControllerDelegate, RSKImageCropViewControllerDataSource>

@end

@implementation PHInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    WS(ws);
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [GGlobalUser getUserInfo:NO finish:^(BOOL success) {
            [ws.tableView.mj_header endRefreshing];
            if (success) {
                [ws.tableView reloadData];
            }
        }];
    }];
    [self.tableView.mj_header beginRefreshing];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [NNCDC addObserver:self selector:@selector(userInfoChaned:) name:kUserInfoChangedNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [NNCDC removeObserver:self name:kUserInfoChangedNotification object:nil];
}

-(void)userInfoChaned:(NSNotification *)notification {
    [self.tableView reloadData];
}

-(void)modifyAvatar {
    WS(ws);
    QMUIAlertController *actionSheet = [QMUIAlertController alertControllerWithTitle:NSLocalizedString(@"modify_avatar", nil) message:nil preferredStyle:QMUIAlertControllerStyleActionSheet];
    QMUIAlertAction *takePhotoAction = [QMUIAlertAction actionWithTitle:NSLocalizedString(@"take_photo", nil) style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
        if ([CameraUtils isCameraOK]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.navigationBar.tintColor = UIColorWhite;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            if ([CameraUtils isRearCameraAvailable]) {
                picker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
            }
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            picker.mediaTypes = mediaTypes;
            picker.delegate = self;
            [ws.navigationController presentViewController:picker animated:YES completion:nil];
        }
    }];
    [actionSheet addAction:takePhotoAction];
    
    QMUIAlertAction *selectAlbumAction = [QMUIAlertAction actionWithTitle:NSLocalizedString(@"select_from_album", nil) style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
        
        if ([CameraUtils isPhotoLibraryAvailable]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.navigationBar.tintColor = UIColorWhite;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            picker.mediaTypes = mediaTypes;
            picker.delegate = self;
            [ws.navigationController presentViewController:picker animated:YES completion:nil];
        } else {
            [KKAlert warningWithText:NSLocalizedString(@"tips_album_not_support", nil)];
        }
    }];
    [actionSheet addAction:selectAlbumAction];
    
    QMUIAlertAction *cancelAction = [QMUIAlertAction actionWithTitle:NSLocalizedString(@"btn_cancel", nil) style:QMUIAlertActionStyleCancel handler:nil];
    [actionSheet addAction:cancelAction];

    [actionSheet showWithAnimated:YES];
}

-(void)modifyNickname {
    [KKAlert inputWithTitle:NSLocalizedString(@"modify_nickname", nil) text:GGlobalUser.info.nick_name placeholder:NSLocalizedString(@"input_nickname", nil) ok:^(NSString *string) {
        LOG(@"string %@", string);
        
        [GGlobalUser modify:@{ @"nick_name": string } ];
    }];
}

-(void)modifySex {
    QMUIDialogSelectionViewController *dialog = [[QMUIDialogSelectionViewController alloc] init];
    dialog.title = NSLocalizedString(@"modify_gender", nil);
    dialog.items = @[ NSLocalizedString(@"Male", nil), NSLocalizedString(@"Female", nil) ];
    dialog.selectedItemIndex = [GGlobalUser.info.sex integerValue];
    [dialog addCancelButtonWithText:NSLocalizedString(@"btn_cancel", nil) block:nil];
    [dialog addSubmitButtonWithText:NSLocalizedString(@"btn_ok", nil) block:^(QMUIDialogViewController *dialogViewController) {
        QMUIDialogSelectionViewController *alert = (QMUIDialogSelectionViewController *)dialogViewController;
        [alert hide];
        
        LOG(@"selected %zi", alert.selectedItemIndex);
        
        NSString *str = [NSString stringWithFormat:@"%d",(int)alert.selectedItemIndex];
        [GGlobalUser modify:@{ @"sex": str }];
    }];
    [dialog show];
}

-(void)modifyBirthday {
    KKDatePicker *dialog = [[KKDatePicker alloc] init];
    dialog.title = NSLocalizedString(@"modify_birthday", nil);
    dialog.datePicker.datePickerMode = UIDatePickerModeDate;
    if (!KIsBlankString(GGlobalUser.info.birthday)) {
        dialog.datePicker.date = [NSDate date:GGlobalUser.info.birthday WithFormat:kYMDFormart];
    }
    [dialog addCancelButtonWithText:NSLocalizedString(@"btn_cancel", nil) block:nil];
    [dialog addSubmitButtonWithText:NSLocalizedString(@"btn_ok", nil) block:^(QMUIDialogViewController *dialogViewController) {
        KKDatePicker *alert = (KKDatePicker *)dialogViewController;
        [alert hide];
        
        LOG(@"date %@", alert.datePicker.date);
        
        NSString *str = [alert.datePicker.date stringWithFormat:kYMDFormart];
        [GGlobalUser modify:@{ @"birthday": str } ];
    }];
    [dialog show];
}

-(void)modifyAddress {
    
    KKDialogTextViewController *dialog = [[KKDialogTextViewController alloc] init];
    dialog.title = NSLocalizedString(@"modify_address", nil);
    dialog.textView.text = GGlobalUser.info.address;
    dialog.textView.placeholder = NSLocalizedString(@"input_address", nil);
    [dialog addCancelButtonWithText:NSLocalizedString(@"btn_cancel", nil) block:nil];
    [dialog addSubmitButtonWithText:NSLocalizedString(@"btn_ok", nil) block:^(QMUIDialogViewController *dialogViewController) {
        KKDialogTextViewController *alert = (KKDialogTextViewController*)dialogViewController;
        
        LOG(@"string %@",alert.textView.text);
        
        [alert hide];
        
        NSString *str = alert.textView.text;
        [GGlobalUser modify:@{ @"address": str }];
    }];
    [dialog show];
}

#pragma mark - UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    LOG(@"info %@",info);
    [picker dismissViewControllerAnimated:NO completion:nil];
    
    UIImage *imgage = [info objectForKey:UIImagePickerControllerOriginalImage];
    RSKImageCropViewController *imageCropVC = [[RSKImageCropViewController alloc] initWithImage:imgage cropMode:RSKImageCropModeCircle];
    imageCropVC.rotationEnabled = YES;
    imageCropVC.delegate = self;
    imageCropVC.dataSource = self;
    [self.navigationController presentViewController:imageCropVC animated:YES completion:^{
        
        if (@available(iOS 11.0, *)) {
            NSURL *url = [info objectForKey:UIImagePickerControllerImageURL];
            BOOL result = [FM removeItemAtURL:url error:nil];
            if (!result) {
                LOG(@"%@ remove failed", url);
            }
        } else {
            // Fallback on earlier versions
        }
    }];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - RSKImageCropViewControllerDataSource
-(CGRect)imageCropViewControllerCustomMaskRect:(RSKImageCropViewController *)controller {
    return CGRectMake(0, (SCREEN_HEIGHT - APP_WIDTH)/2, APP_WIDTH, APP_WIDTH);
}

- (UIBezierPath *)imageCropViewControllerCustomMaskPath:(RSKImageCropViewController *)controller{
    return [UIBezierPath bezierPathWithRect:controller.maskRect];
}

- (CGRect)imageCropViewControllerCustomMovementRect:(RSKImageCropViewController *)controller{
    return controller.maskRect;
}

#pragma mark - RSKImageCropViewControllerDelegate
- (void)imageCropViewControllerDidCancelCrop:(RSKImageCropViewController *)controller{
    [controller dismissViewControllerAnimated:YES completion:nil];
}

- (void)imageCropViewController:(RSKImageCropViewController *)controller didCropImage:(UIImage *)croppedImage usingCropRect:(CGRect)cropRect rotationAngle:(CGFloat)rotationAngle {
    LOG(@"croppedImage %@",croppedImage);
    
    [controller dismissViewControllerAnimated:YES completion:nil];
    
    [GGlobalUser uploadAvatar:croppedImage];
}

#pragma mark - UITableViewDataSource & UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 6;
    }
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20.0f;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectMake(0, 0, APP_WIDTH, 20)];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 0) {
        return 100.0f;
    } else {
        return TableViewCellNormalHeight;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *identi = @"cell";
        QMUITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identi];
        if (!cell) {
            cell = [[QMUITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identi];
        }
        if (indexPath.row == 0) {
            cell.textLabel.text = NSLocalizedString(@"avatar", nil);
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            
            NSURL *url = [NSURL URLWithString:GGlobalUser.info.img];
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(APP_WIDTH - 110, 10, 80, 80)];
            imageView.layer.cornerRadius = 4.0f;
            imageView.layer.masksToBounds = YES;
            [imageView sd_setImageWithURL:url placeholderImage:UIImageMake(@"header_default")];
            [cell.contentView addSubview:imageView];
        }
        else if (indexPath.row == 1) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.textLabel.text = NSLocalizedString(@"nickname", nil);
            cell.detailTextLabel.text = GGlobalUser.info.nick_name;
        }
        else if (indexPath.row == 2) {
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.textLabel.text = NSLocalizedString(@"account", nil);
            cell.detailTextLabel.text = [GGlobalUser.info account];
        }
        else if (indexPath.row == 3) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.textLabel.text = NSLocalizedString(@"gender", nil);
            cell.detailTextLabel.text = [GGlobalUser.info genderString];
        }
        else if (indexPath.row == 4) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.textLabel.text = NSLocalizedString(@"birthday", nil);
            cell.detailTextLabel.text = GGlobalUser.info.birthday;
        }
        else if (indexPath.row == 5) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.textLabel.text = NSLocalizedString(@"address", nil);
            cell.detailTextLabel.numberOfLines = 2;
            cell.detailTextLabel.text = GGlobalUser.info.address;
        }
        return cell;
    } else if (indexPath.section == 1) {
        static NSString *identi1 = @"cell1";
        QMUITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identi1];
        if (!cell) {
            cell = [[QMUITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identi1];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        cell.textLabel.text = NSLocalizedString(@"modify_password", nil);
        return cell;
    }
    else {
        static NSString *identi2 = @"cell2";
        QMUITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identi2];
        if (!cell) {
            cell = [[QMUITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identi2];
        }
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.textColor = GQDThemeManager.currentTheme.themeTintColor;
        cell.textLabel.text = NSLocalizedString(@"btn_logout", nil);
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            [self modifyAvatar];
        }
        else if (indexPath.row == 1) {
            [self modifyNickname];
        }
        else if (indexPath.row == 3) {
            [self modifySex];
        }
        else if (indexPath.row == 4) {
            [self modifyBirthday];
        }
        else if (indexPath.row == 5) {
            [self modifyAddress];
        }
    }
    else if (indexPath.section == 1) {
        PHPasswordViewController *passwordVC = [[PHPasswordViewController alloc] init];
        [self.navigationController pushViewController:passwordVC animated:YES];
    }
    else {
        [KKAlert alertWithTitle:NSLocalizedString(@"btn_logout", nil) message:NSLocalizedString(@"tips_logout", nil) cancel:^{
            
        } ok:^{
            APP_DELEGATE.loginSuccess = NO;
        }];
    }
}

- (void)setupNavigationItems {
    [super setupNavigationItems];
    self.title = NSLocalizedString(@"settings_infomation", nil);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
